// pages/edit-info/info-base/info-base.js
const cityData = require('../../utils/picker.city.js')
// pages/mine/mine.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 时间选择器参数
    type: 2,
    startYear: 1980,
    endYear: 2030,
    cancelColor: "#888",
    color: "#90d7ec",
    setDateTime: "",
    result: "",
    // 页面信息参数
    mainInfo: {
      isBagEating: false, // 包吃
      encase: false, // 包住
      isTrafficSubsidy: false, //交通补贴
      settlement: 1,
      royalty: false, //有提成
      sex: 3
    },
    uid: "",
    iconHidden: true,
    showPickerStatus: false,
    animationData: "",

  },
  // 选择是否包吃包住
  switch1Change(e) {
    let type = e.currentTarget.dataset.type;
    this.setData({
      ['mainInfo.' + type]: e.detail.value
    })
  },
  getLocal() {
    let _this = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        wx.chooseLocation(
          {
            latitude,
            longitude,
            success: (el) => {
              console.log(el)
              const db = wx.cloud.database()
              _this.setData({
                'mainInfo.detailPlace': el.name || el.address,
                'mainInfo.point': new db.Geo.Point(el.longitude, el.latitude)
              })
            }
          },

        )
      }, fail: res => {
        console.log(res)
        wx.showModal({
          title: '警告',
          content: '您点击了拒绝授权,将无法正常调用地理位置,点击确定重新获取授权。',
          success: function (res) {
            if (res.confirm) {
              //重点:从这里开始就是重新授权调取
              wx.openSetting({
                success: (res) => {
                  if (res.authSetting["scope.userLocation"]) { //如果用户重新同意了授权登录scope.userLocation是表示位置授权 true/false
                    const latitude = res.latitude
                    const longitude = res.longitude
                    wx.chooseLocation(
                      {
                        latitude,
                        longitude,
                        success: (el) => {
                          console.log(el)
                          const db = wx.cloud.database()
                          _this.setData({
                            'mainInfo.detailPlace': el.name || el.address,
                            'mainInfo.point': new db.Geo.Point(el.longitude, el.latitude)
                          })
                        }
                      },

                      
                    )
                  }
                }, fail: function (res) {

                }
              })
              //重点:调取结束
            }
          }
        })
      }
    })
  },
  // 表单提交和重置
  formSubmit: function (e) {
    for (let key in e.detail.value) {
      if (e.detail.value[key] == '') {
        wx.showToast({
          title: '信息不完善',
          icon: 'none'
        })
        return
      }
      this.setData({
        ['mainInfo.' + key + '']: e.detail.value[key]
      })
    }
    var _this = this
    wx.showModal({
      title: '提示',
      content: '确定提交修改的信息吗？',
      confirmColor: "#90d7ec",
      success(res) {
        if (res.confirm) {
          // 提交修改信息
          let openid = app.getCache('openid')
          const db = wx.cloud.database()
          const _ = db.command
          console.log('form发生了submit事件，携带数据为：', _this.data.mainInfo)
          db.collection('job')
            .add({
              data:
              {
                userId: openid,
                ..._this.data.mainInfo
              }
            }).then(res => {
              console.log(res);
              wx.showToast({
                title: '保存成功',
                duration: 1500,
                icon: 'success'
              })
              setTimeout(() => {
                wx.navigateBack({
                  delta: 1,
                })

              }, 1500)
            })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  formReset: function () {
    console.log('form发生了reset事件')
  },
  // 选择性别
  sexChange(e) {
    var sex = parseInt(e.detail.currentKey)
    this.setData({
      'mainInfo.sex': sex
    })
  },
  // 显示时间选择器
  show: function (e) {
    let timetype = e.target.dataset.type;
    this.setData({
      timetype,
      type: 1,
      cancelColor: "#888",
      color: "#90d7ec",
      setDateTime: this.data.mainInfo[timetype],
      startYear: 2020,
      endYear: 2050
    }, this.dateTime.show())

  },
  // 改变时间
  change: function (e) {
    this.setData({
      ['mainInfo.' + this.data.timetype]: e.detail.result
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //初始化城市选择器数据
    this.setData({
      proviceArr: this.toArr(cityData),
      cityArr: this.toArr(cityData[0].children),
      districtArr: this.toArr(cityData[0].children[0].children),
    })
  },
  onReady: function (options) {
    this.dateTime = this.selectComponent("#tui-dateTime-ctx")
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var _this = this

  },
  toArr(object) {
    let arr = [];
    for (let i in object) {
      arr.push(object[i].name);
    }
    return arr;
  },
  /**
   * 城市选择器相关
   */
  //picker change切换事件
  columnPicker: function (e) {
    let value = e.detail.value;
    //如果两者下标不一致，表示滚动过
    if (this.data.value[0] !== value[0]) {
      this.setData({
        proviceArr: this.data.proviceArr,
        cityArr: this.toArr(cityData[value[0]].children),
        districtArr: this.toArr(cityData[value[0]].children[0].children),
        value: [value[0], 0, 0]
      })
    } else if (this.data.value[1] !== value[1]) {
      this.setData({
        proviceArr: this.data.proviceArr,
        cityArr: this.data.cityArr,
        districtArr: this.toArr(cityData[value[0]].children[value[1]].children),
        value: [value[0], value[1], 0]
      })
    } else {
      this.setData({
        value: value
      })
    }
  },
  //确定按钮
  picker: function (e) {
    let value = this.data.value;
    if (cityData.length > 0) {
      let provice = cityData[value[0]].name
      let city = cityData[value[0]].children[value[1]].name
      let district = cityData[value[0]].children[value[1]].children[value[2]].name;
      console.log(provice, city, district)
      this.setData({
        "mainInfo.place": (provice + ',' + city + ',' + district),
        text: [provice, city, district],
        showPickerStatus: false,
        nativePlace: provice + ' ' + city + ' ' + district
      })
    }
  },
  // 显示picker-view
  showPicker: function () {
    var animation = wx.createAnimation({
      duration: 220,
      timingFunction: "linear",
      delay: 0
    })
    animation.translateY(500).step()
    this.setData({
      animationData: animation.export(),
      showPickerStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  // 隐藏picker-view
  hidePicker: function () {
    this.setData({
      showPickerStatus: false
    })
  },
})